package com.hao.wms.service.impl;

import com.hao.wms.dao.IStockOutcomeBillDao;
import com.hao.wms.domain.StockOutcomeBill;
import com.hao.wms.domain.StockOutcomeBillItem;
import com.hao.wms.query.PageResult;
import com.hao.wms.query.QueryObject;
import com.hao.wms.service.IProductStockService;
import com.hao.wms.service.IStockOutcomeBillService;
import com.hao.wms.util.UserContext;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

public class StockOutcomeBillServiceImpl implements IStockOutcomeBillService {
    private IStockOutcomeBillDao dao;
    private IProductStockService productStockService;

    public void setDao(IStockOutcomeBillDao dao) {
        this.dao = dao;
    }

    public void setProductStockService(IProductStockService productStockService) {
        this.productStockService = productStockService;
    }


    @Override
    public void save(StockOutcomeBill stockOutcomeBill) {
        stockOutcomeBill.setInputUser(UserContext.getUser());
        stockOutcomeBill.setInputTime(new Date());
        stockOutcomeBill.setStatus(StockOutcomeBill.NORMAL);
        parseItems(stockOutcomeBill);
        dao.save(stockOutcomeBill);

    }

    private void parseItems(StockOutcomeBill stockOutcomeBill) {
        stockOutcomeBill.setTotalNumber(BigDecimal.ZERO);
        stockOutcomeBill.setTotalAmount(BigDecimal.ZERO);
        for (StockOutcomeBillItem item : stockOutcomeBill.getItems()) {
            item.setBill(stockOutcomeBill);
            item.setAmount(item.getSalePrice().multiply(item.getNumber()).setScale(2, BigDecimal.ROUND_HALF_UP));
            stockOutcomeBill.setTotalNumber(stockOutcomeBill.getTotalNumber().add(item.getNumber()));
            stockOutcomeBill.setTotalAmount(stockOutcomeBill.getTotalAmount().add(item.getAmount()));
        }
    }

    @Override
    public void update(StockOutcomeBill stockOutcomeBill) {
        if (stockOutcomeBill.getStatus() == StockOutcomeBill.NORMAL) {
            parseItems(stockOutcomeBill);
            dao.update(stockOutcomeBill);
        }

    }

    @Override
    public void delete(StockOutcomeBill stockOutcomeBill) {
        dao.delete(stockOutcomeBill);

    }

    @Override
    public StockOutcomeBill get(Long id) {
        return dao.get(id);
    }

    @Override
    public List<StockOutcomeBill> list() {
        return dao.list();
    }

    @Override
    public PageResult query(QueryObject qo) {
        return dao.query(qo);
    }

    @Override
    public void audit(Long id) {
        StockOutcomeBill bill = dao.get(id);
        if (bill.getStatus() == StockOutcomeBill.NORMAL) {
            bill.setAuditor(UserContext.getUser());
            bill.setAuditTime(new Date());
            bill.setStatus(StockOutcomeBill.AUDIT);
            for (StockOutcomeBillItem Item : bill.getItems()) {
                productStockService.outcome(bill.getDepot(), Item.getProduct(),Item.getNumber());
            }
            dao.update(bill);
        }
    }
}
